package com.lbs.jiepiaisi.fragment;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.activity.WorkOrderActivity;
import com.lbs.jiepiaisi.base.BaseFragment;
import com.lbs.jiepiaisi.bean.LoginPhoneResultBean;
import com.lbs.jiepiaisi.biz.LoginPhoneBiz;
import com.lbs.jiepiaisi.manager.SharePreferenceManager;
import com.lbs.jiepiaisi.utils.ButtonUtil;
import com.lbs.jiepiaisi.utils.Constant;
import com.lbs.jiepiaisi.utils.LocationPerUtil;
import com.lbs.jiepiaisi.utils.PhotoPerUtil;
import com.lbs.jiepiaisi.utils.ValidUtil;
import com.lbs.jiepiaisi.view.WaitingDialogControll;


/**
 * 工单
 */
public class WorkOrderFragment extends BaseFragment {
    private static final int BAIDU_READ_PHONE_STATE = 100;
    private EditText mEditText;
    private Button mLoginBtn;

    private LoginReceiver mLoginReceiver;

    private CheckBox mSelCK;

    public SharePreferenceManager mSharePreference = null;

    @Override
    public View initView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_work_order, null);
        mSharePreference = new SharePreferenceManager(mContext);
        mLoginReceiver = new LoginReceiver();
        getActivity().getApplicationContext().registerReceiver(mLoginReceiver, new IntentFilter(Constant.ACCOUNT_INSTALLER_LOGIN));
        return view;
    }

    @Override
    protected void getExtras(View view) {


    }

    @Override
    protected void findView(View view) {
        mEditText = (EditText) view.findViewById(R.id.et_username);
        //mEditText.setText("15866786713");
        mLoginBtn = (Button) view.findViewById(R.id.btn_ok);
        mSelCK = (CheckBox) view.findViewById(R.id.ck_tel);
        mSelCK.setChecked(true);

        String phone = mSharePreference.getString(Constant.WORK_ORDER_PHONE, "");
        if (!"".equals(phone)) {
            mEditText.setText(phone);
        }
    }

    @Override
    protected void setListener(View view) {
        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("".equals(mEditText.getText().toString())) {
                    Toast.makeText(mContext, "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(!ValidUtil.validPhone(mEditText.getText().toString())){
                    Toast.makeText(mContext, "请输入正确的手机号码", Toast.LENGTH_LONG).show();
                    return;
                }
                if (LocationPerUtil.checkLocationPermission(getActivity())) {
                    if(PhotoPerUtil.checkCameraPermission(getActivity())){
                        WaitingDialogControll.showWaitingDialog(getContext());
                        if (ButtonUtil.isFastClick()) {
                            new LoginPhoneBiz().phoneBiz(mEditText.getText().toString());
                        }
                    }else {
                        Toast.makeText(mContext, "请打开相机权限", Toast.LENGTH_LONG).show();
                    }

                } else {
                    Toast.makeText(mContext, "请打开定位权限", Toast.LENGTH_LONG).show();
                }
//                if(showContacts()){
//


            }
        });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().getApplicationContext().unregisterReceiver(mLoginReceiver);
    }

    //接收登录结果
    class LoginReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            LoginPhoneResultBean loginPhoneResultBean = (LoginPhoneResultBean) intent.getSerializableExtra(Constant.KEY_DATA);
            if (loginPhoneResultBean.getStatus() == Constant.STATUS_OK) {
                if (mSelCK.isChecked()) {
                    mSharePreference.put(Constant.WORK_ORDER_PHONE, mEditText.getText().toString());
                }
                Intent workOrder = new Intent(getActivity(), WorkOrderActivity.class);
                workOrder.putExtra("phoneLogin", loginPhoneResultBean);
                startActivity(workOrder);
            } else if (loginPhoneResultBean.getStatus() == Constant.STATUS_NETWORK_ERROR) {
                Toast.makeText(mContext, "登录失败", Toast.LENGTH_LONG).show();
            } else if (loginPhoneResultBean.getStatus() == Constant.STATUS_NO_NET) {
                Toast.makeText(mContext, "请检查网络", Toast.LENGTH_SHORT).show();
            }
            WaitingDialogControll.dismissWaitingDialog();

        }
    }


    public boolean showContacts() {
        if (ActivityCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this.getActivity(), Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this.getActivity(), "没有开启权限,请手动开启定位权限", Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(this.getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE}, BAIDU_READ_PHONE_STATE);
        }
        return true;
    }

    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this.getActivity(), "获取位置权限成功，请登录", Toast.LENGTH_SHORT).show();
                } else {
                    // 没有获取到权限，做特殊处理
                    Toast.makeText(this.getActivity(), "获取位置权限失败，请手动开启", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }
}
